#!/bin/bash

# 系统健康检查脚本
# 用于监控所有服务的运行状态

PROJECT_NAME="learning-platform"
LOG_FILE="/var/log/${PROJECT_NAME}-health.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 记录日志
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG_FILE
}

# 检查服务状态
check_service() {
    local service_name=$1
    local url=$2
    local expected_status=${3:-200}
    
    echo -n "检查 $service_name... "
    
    if curl -s -f -o /dev/null --max-time 10 "$url"; then
        echo -e "${GREEN}正常${NC}"
        return 0
    else
        echo -e "${RED}异常${NC}"
        log "警告: $service_name 服务异常 ($url)"
        return 1
    fi
}

# 检查系统资源
check_system_resources() {
    echo "=== 系统资源检查 ==="
    
    # CPU使用率
    cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F'%' '{print $1}')
    echo "CPU使用率: ${cpu_usage}%"
    
    # 内存使用率
    memory_info=$(free | grep Mem)
    total_memory=$(echo $memory_info | awk '{print $2}')
    used_memory=$(echo $memory_info | awk '{print $3}')
    memory_usage=$(awk "BEGIN {printf \"%.1f\", $used_memory/$total_memory*100}")
    echo "内存使用率: ${memory_usage}%"
    
    # 磁盘使用率
    disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
    echo "磁盘使用率: ${disk_usage}%"
    
    # 警告阈值检查
    if (( $(echo "$cpu_usage > 80" | bc -l) )); then
        log "警告: CPU使用率过高 ($cpu_usage%)"
    fi
    
    if (( $(echo "$memory_usage > 85" | bc -l) )); then
        log "警告: 内存使用率过高 ($memory_usage%)"
    fi
    
    if [ $disk_usage -gt 90 ]; then
        log "警告: 磁盘使用率过高 ($disk_usage%)"
    fi
    
    echo ""
}

# 检查数据库连接
check_database() {
    echo -n "检查数据库连接... "
    
    if mysql -h${DB_HOST:-localhost} -P${DB_PORT:-3306} -u${DB_USERNAME:-learning} -p${DB_PASSWORD} -e "SELECT 1;" > /dev/null 2>&1; then
        echo -e "${GREEN}正常${NC}"
        return 0
    else
        echo -e "${RED}异常${NC}"
        log "错误: 数据库连接失败"
        return 1
    fi
}

# 检查日志文件大小
check_log_sizes() {
    echo "=== 日志文件检查 ==="
    
    log_dirs=(
        "/var/log/learning-platform"
        "/opt/learning-platform/current/backend/logs"
    )
    
    for log_dir in "${log_dirs[@]}"; do
        if [ -d "$log_dir" ]; then
            large_logs=$(find "$log_dir" -name "*.log" -size +100M 2>/dev/null)
            if [ -n "$large_logs" ]; then
                echo -e "${YELLOW}发现大型日志文件:${NC}"
                echo "$large_logs"
                log "提醒: 发现大型日志文件需要清理"
            fi
        fi
    done
    echo ""
}

# 主健康检查
main_health_check() {
    echo "======================================"
    echo "学习平台健康检查报告"
    echo "时间: $(date)"
    echo "======================================"
    
    # 系统资源检查
    check_system_resources
    
    # 服务检查
    echo "=== 服务状态检查 ==="
    failed_services=0
    
    # 数据库检查
    check_database || ((failed_services++))
    
    # 后端服务检查
    check_service "后端服务" "http://localhost:8080/api/v1/health" || ((failed_services++))
    
    # AI服务检查
    check_service "AI服务" "http://localhost:8000/health" || ((failed_services++))
    
    # 前端服务检查
    check_service "前端服务" "http://localhost/" || ((failed_services++))
    
    echo ""
    
    # 日志检查
    check_log_sizes
    
    # systemd服务状态检查
    echo "=== Systemd服务状态 ==="
    services=("learning-backend" "learning-ai" "nginx" "mysql")
    
    for service in "${services[@]}"; do
        if systemctl is-active --quiet "$service"; then
            echo -e "$service: ${GREEN}运行中${NC}"
        else
            echo -e "$service: ${RED}未运行${NC}"
            log "错误: $service 服务未运行"
            ((failed_services++))
        fi
    done
    
    echo ""
    echo "======================================"
    
    if [ $failed_services -eq 0 ]; then
        echo -e "${GREEN}✓ 所有检查通过，系统运行正常${NC}"
        log "信息: 健康检查通过"
        exit 0
    else
        echo -e "${RED}✗ 发现 $failed_services 个问题，请检查系统状态${NC}"
        log "错误: 健康检查发现 $failed_services 个问题"
        exit 1
    fi
}

# 自动修复功能
auto_repair() {
    echo "=== 自动修复模式 ==="
    
    # 重启失败的服务
    services=("learning-backend" "learning-ai" "nginx")
    
    for service in "${services[@]}"; do
        if ! systemctl is-active --quiet "$service"; then
            echo "重启服务: $service"
            systemctl restart "$service"
            sleep 5
            
            if systemctl is-active --quiet "$service"; then
                echo -e "${GREEN}✓ $service 重启成功${NC}"
                log "信息: $service 服务自动重启成功"
            else
                echo -e "${RED}✗ $service 重启失败${NC}"
                log "错误: $service 服务自动重启失败"
            fi
        fi
    done
}

# 清理日志
cleanup_logs() {
    echo "=== 清理旧日志 ==="
    
    # 清理7天前的日志
    find /var/log/learning-platform -name "*.log" -mtime +7 -delete 2>/dev/null || true
    find /opt/learning-platform/current/backend/logs -name "*.log" -mtime +7 -delete 2>/dev/null || true
    
    echo "日志清理完成"
    log "信息: 执行日志清理"
}

# 脚本参数处理
case "${1:-check}" in
    "check")
        main_health_check
        ;;
    "repair")
        auto_repair
        main_health_check
        ;;
    "cleanup")
        cleanup_logs
        ;;
    "monitor")
        # 持续监控模式
        while true; do
            main_health_check
            echo "等待60秒后进行下次检查..."
            sleep 60
        done
        ;;
    *)
        echo "用法: $0 [check|repair|cleanup|monitor]"
        echo "  check   - 执行健康检查 (默认)"
        echo "  repair  - 自动修复后执行检查"
        echo "  cleanup - 清理旧日志文件"
        echo "  monitor - 持续监控模式"
        exit 1
        ;;
esac





